package com.lun.blog.service.impl;

import com.lun.blog.dto.MessageChild;
import com.lun.blog.dto.MessageDto;
import com.lun.blog.pojo.Message;
import com.lun.blog.pojo.Type;
import com.lun.blog.repostory.MessageRepository;
import com.lun.blog.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @Function : MessageServiceImpl
 * @Description:
 * @Param:
 * @version: v1.0.0
 * @author: fanglj5
 * @date : 2021/3/13
 * Modification History:
 * Date Author Version Description
 * -------------------------------------------------------------
 * 时间 作者 版本号 修改原因
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageRepository messageRepository;

    @Override
    public void addMessage(Message message) {
        Long messsageId = message.getParentMessage().getId();
        if(messsageId != -1){
            message.setState("2");
            message.setParentMessage(messageRepository.getOne(messsageId));
        }else {
            message.setState("1");
            message.setParentMessage(null);
        }
        message.setCreateTime(new Date());
        messageRepository.save(message);
    }

    @Override
    public void deleteMessage(Message message) {
        messageRepository.delete(message);
    }

    @Override
    public void explain(Long id) {
        Optional<Message> message = messageRepository.findById(id);
        Message newMessage = message.get();
        newMessage.setState("2");
        messageRepository.save(newMessage);
    }

    @Override
    public Page<Message> pageMessage(Pageable pageable) {
        Page<Message> page = messageRepository.findAll(new Specification<Message>() {
            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.<Message>get("state"),"1"));
                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
      //  List<Message> collect = page.stream().filter(message -> !message.getState().equals("2")).collect(Collectors.toList());
       // Page list = new PageImpl(collect,pageable,page.getTotalElements());
        return page;
    }

    @Override
    public Message findById(Long id) {
        return messageRepository.findById(id).get();
    }
    @Override
    public Long countMessage() {
        return messageRepository.count();
    }
    @Override
    public List<Message> findAll() {
      //todo 先查询顶级留言 再根据顶级留言区查留言下面的评论
        List<Message> message = messageRepository.findMessage();
        return eachMessage(message);
    }


    /**
     * 根据树的根节点去获取节点信息，将一棵不知道深度的树转为深度是2的树
     * @param root
     * @return
     */
    private List<Message> eachMessage(List<Message> root){
        List<Message> returnList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(root)){
            for (Message message : root) {
                Message message1 = new Message();//新的节点数据
                BeanUtils.copyProperties(message,message1);
                List<Message> messages = this.childMessage(new ArrayList<>(), message);
                //删除根节点
                if(!CollectionUtils.isEmpty(messages)){
                    Iterator<Message> iterator = messages.iterator();
                    while (iterator.hasNext()){
                        Message next = iterator.next();
                        if(next.getId().equals(message.getId())){
                            iterator.remove();
                        }
                    }
                    message1.setReplayMessage(messages);
                }
               returnList.add(message1);
            }
        }
        return returnList;
    }

    /**
     * 根据父节点寻找子节点信息
     * @param list
     * @param message
     * @return
     */
    private List<Message> childMessage(List<Message> list,Message message){
        List<Message> childMessage = messageRepository.findByParentMessage_Id(message.getId());
        if(!CollectionUtils.isEmpty(childMessage)){
            for (Message message1 : childMessage) {
                message1.setParentMessage(message);
                childMessage(list,message1);
            }
        }
        list.add(message);
        return list;
    }


}
